package cn.xdd.servlet.powers;

import cn.xdd.dao.BookDao;
import cn.xdd.entity.Book;
import cn.xdd.entity.BookMsgJson;
import cn.xdd.entity.ReadPageJson;
import cn.xdd.entity.allbookJson;
import com.google.gson.Gson;
import org.apache.log4j.Logger;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author user_xdd
 * @Date 2022-04-02 14:05
 * @description
 * @return
 */
@WebServlet(urlPatterns = {"/bookservlet"})
public class booksevlet extends GenericServlet {
    private static final Logger LOGGER = Logger.getLogger(booksevlet.class);

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");//设置请求中文编码
        response.setContentType("text/html;charset=utf-8");//设置响应中文编码
        HttpSession session = request.getSession();


        BookDao bookDao = new BookDao();
        Gson gson = new Gson();
//        option：getRecommend
        String option = request.getParameter("option");
        try {
            switch (option) {
                case "getRecommend": {

                    List<Book> books = bookDao.getRecommend();
                    String json = gson.toJson(books);
                    LOGGER.debug("    books:" + books);
                    response.getWriter().println(json);

                    break;
                }
                case "saveid": {
                    Integer id = Integer.parseInt(request.getParameter("id"));
                    LOGGER.debug("   saveid id:" + id);
                    request.getSession().setAttribute("readBookId", id);
                    response.sendRedirect("/BookMsg.html");


                    break;
                }
//                读取readBookId返回一个json 对象
                case "getreadId": {
                    Integer readBookId = (Integer) request.getSession().getAttribute("readBookId");
                    Book book = bookDao.getBookByid(readBookId);
                    BookMsgJson bookMsgJson = new BookMsgJson();

//                    获得当前书的所有章节名称

                    String Path = request.getServletContext().getRealPath("/") + "data/book" + File.separator + book.getBook_address();
                    ArrayList<String> list = new ArrayList<String>(0);//用arraylist保存扫描到的路径
                    File file = new File(Path);
                    String[] list1 = file.list();
                    List<String> filenames = Arrays.asList(list1);
                    LOGGER.debug("    filenames:" + filenames);


//                    填充数据
                    bookMsgJson.setBook(book);
                    bookMsgJson.setCid(filenames);
                    String json = gson.toJson(bookMsgJson);
                    LOGGER.debug("    json:" + json);

                    response.getWriter().println(json);
                    break;
                }
                case "saveChapterId": {
                    String ChapterId = request.getParameter("ChapterId");
                    LOGGER.debug("    ChapterId:" + ChapterId);
                    request.getSession().setAttribute("ChapterId", ChapterId);
                    response.sendRedirect("/ReadBook.html");
                    break;
                }
                case "getChapterId": {
                    String chapterId = (String) request.getSession().getAttribute("ChapterId");
                    LOGGER.debug("    chapterId:" + chapterId);
//                    6edc91c9736b4b7caffb209cf1c58d7d/00001这里是第1章节.txt
//                    File file= new File("/src/main/webapp/data/book/" + chapterId);
                    String Path = request.getServletContext().getRealPath("/") + "data" + File.separator + "book" + File.separator + chapterId;
                    LOGGER.debug("    Path:" + Path);
                    File file = new File(Path);
                    LOGGER.debug("    file:" + file);

                    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

                    List<String> readMsg = new ArrayList<>();
                    String s;
                    while ((s = bufferedReader.readLine()) != null) {//使用readLine方法，一次读一行
                        readMsg.add(s);
                    }


                    bufferedReader.close();

                    int b = chapterId.indexOf('/');
                    int e = chapterId.lastIndexOf('.');
                    String pagename = chapterId.substring(b + 6, e);
//                     LOGGER.debug("    b:"+b);
//                     LOGGER.debug("    e:"+e);
                    LOGGER.debug("    pagename:" + pagename);
                    Integer readBookId = (Integer) request.getSession().getAttribute("readBookId");
                    Book book = bookDao.getBookByid(readBookId);
                    ReadPageJson readPageJson = new ReadPageJson();

                    readPageJson.setPagename(pagename);
                    readPageJson.setPages(readMsg);
                    readPageJson.setBook(book);

                    String json = gson.toJson(readPageJson);
                    LOGGER.debug("    json:" + json);
                    response.getWriter().println(json);
                    break;
                }
                case "allBook": {

                    String allBookpageid = (String) request.getSession().getAttribute("allBookpageid");
//                    总页数
                    int step = 20;
                    Integer nums = bookDao.getbookNums();
//                    int pagenums = nums / step == 0 ? nums / step : nums / step + 1;
                    int pagenums = (int) Math.ceil(nums / step);
//                    当前页数 默认为1
                    int nowpage = 1;
//                    返回的列表
                    allbookJson allbookJson = new allbookJson();
//                    没有参数
                    LOGGER.debug("    allBookpageid:" + allBookpageid);
                    if (allBookpageid == null) {
                        List<Book> getlimi = bookDao.getlimi(0, step);
                        allbookJson.setDatas(getlimi);
                    } else {

                        int num= Integer.parseInt(allBookpageid);
                        nowpage=num;
                        int begin=(num-1)*20;
                        List<Book> getlimi = bookDao.getlimi(begin, step);
                        allbookJson.setDatas(getlimi);
                    }

                    allbookJson.setPages(pagenums);

                    allbookJson.setNowpage(nowpage);

                    String json = gson.toJson(allbookJson);

                    LOGGER.debug("    json:" + json);
                    response.getWriter().print(json);
//                    http://localhost:8086/bookservlet?option=allBook
                    break;
                }
                case "allbookSavepageId":{
                    String allBookpageid = request.getParameter("allBookpageid");
                     LOGGER.debug("    allBookpageid:"+allBookpageid);
                    session.setAttribute("allBookpageid",allBookpageid);
                    response.sendRedirect("/allbook.html");

                    break;
                }
//                返回查到的数据
                case "findB":{
                    String searchSt = request.getParameter("searchSt");
                     LOGGER.debug("    searchSt:"+searchSt);
                    List<Book> book = bookDao.findBook(searchSt);
                    String json = gson.toJson(book);
                     LOGGER.debug("    json:"+json);
                     response.getWriter().println(json);
                    break;
                }
                default:
                    LOGGER.error("没有传递参数");

            }
        } catch (SQLException | NullPointerException e) {
            e.printStackTrace();
        }
    }


}

